import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import Base from './children/base';
// 自助取数
//  --取数配置
//  --任务管理
import indexApplication from './children/indexApplication';
// 指标管理
import indexManage from './children/indexManage';
// 指标市场
import indexMarket from './children/indexMarket';
// 指标开发
import indexDevelop from './children/indexDevelop';
// 审批中心
import approvalCenter from './children/approvalCenter'
// 系统管理
import systemManage from './children/systemManage'

import { ElMessage, ElMessageBox } from 'element-plus/lib/index';
import { useUserStore } from '@/store/user';
import { usePermissionStore } from '@/store/permission';
import { getCookie, checkUserMenuPage, backPreviousSys } from '@/utils/util';
import { http, URL, getUrl } from '@/utils/http';
import CrumbsAddon from '@/utils/crumbs-addon/index';
import { store } from '@/store';

/**
 * 获取有权限的路由
 * @param {any} to
 * @param {any} from
 * @param {any} next
 */
function menuTimerInvoke(to: any, from: any, next: any) {
  const permissionStore = usePermissionStore();
  // const { path } = getUrl(
  //   URL.UMS_RULE.USER_RULE,
  //   {
  //     systemCode: 'metricsx',
  //     moduleCode: ''
  //   },
  //   'get'
  // );
  http
    .get(URL.UMS_RULE.USER_RULE + '?systemCode=metricx&moduleCode=', {
      systemCode: 'metricx',
      moduleCode: ''
    })
    .then((res: any) => {
      const { data, code, desc } = res;
      if (code == 0) {
        permissionStore.setButtonRulesList(data.buttonList);
        permissionStore.setPermission(data.menuList);
        next();
        // if (checkUserMenuPage(data.menuList, to.path)) {
        //   next();
        // } else {
        //   ElMessageBox.alert(`您没有访问当前页面的权限，请联系管理员！`, {
        //     confirmButtonText: '确定',
        //     callback: () => {
        //       next('/home');
        //     }
        //   });
        // }
      } else {
        ElMessageBox.alert(desc, {
          confirmButtonText: '确定'
        });
      }
    });
}
/**
 * 获取有权限的路由
 * @param {any} to
 * @param {any} from
 * @param {any} next
 */
function toDo(to: any, from: any, next: any) {
  const permissionStore = usePermissionStore();
  if (!permissionStore.$state.permission.length) {
    menuTimerInvoke(to, from, next);
  } else {
    if (to.matched.length) {
      next();
    } else {
      next('/404');
    }
  }
}

const routes: Array<RouteRecordRaw> = [
  ...Base,
  ...indexApplication,
  ...indexManage,
  ...indexMarket,
  ...indexDevelop,
  ...approvalCenter,
  ...systemManage,
];

NProgress.configure({
  showSpinner: false
});
// console.log(process.env.BASE_URL);
const router = createRouter({
  history: createWebHashHistory(),
  routes
});

router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  // 开启进度条
  NProgress.start();
  if (to.meta.title) {
    document.title = `${process.env.VUE_APP_APPNAME} | ${to.meta.title}`;
  }
  if (!userStore.$state.userLoginMsg) {
    // const { data, code, desc } = await userStore.findByUser();
    const x = http
      .get(`${URL.SSO_USER.VERIFY_TOKEN}?token=${getCookie('access-token')}`)
      .then((res: any) => {
        const { data, code, desc } = res;
        if (code == 0) {
          userStore.setUserInfo(data);
          userStore.setAccessToken(getCookie('access-token'));
          userStore.setMsg('success');
          toDo(to, from, next);
          // set breadcrumb
          setBreadcrumbState(to, from, next);
        } else {
          ElMessageBox.alert(desc, {
            confirmButtonText: '确定',
            callback: () => {
              backPreviousSys('');
            }
          });
        }
      });
  } else {
    toDo(to, from, next);
    // set breadcrumb
    setBreadcrumbState(to, from, next);
  }
});

router.afterEach((to, from, next) => {
  NProgress.done(); // 结束Progress
});

/**
 * 根据路由决定面包屑状态
 */
function setBreadcrumbState(to: any, from: any, next: any) {
  const { name } = to;

  if (name && CrumbsAddon[name]) {
    CrumbsAddon[name](to);
  } else {
    CrumbsAddon['default'](to);
  }
}

export default router;
